#!/bin/bash
set -e
set -x
MYDIR="${0%/*}"
cd "$MYDIR/.."
source "recipes/common.sh"


# RECIPE START initramfs
# depends: dracut-native
# depends: firmware-linux
# depends: linux
# depends: rootfs

kernel_count=`find ${stage}/lib/modules -mindepth 1 -maxdepth 1 -type d | wc -l`
kernel_version=`find ${stage}/lib/modules -mindepth 1 -maxdepth 1 -type d -printf "%f"`
if [ "x$kernel_count" = 'x0' ]; then
	echo "initramfs.sh: no kernels have been found in $stage" >&2
	exit 1
elif [ "x$kernel_count" != 'x1' ]; then
	echo "initramfs.sh: several kernels ${kernel_count} have been found in $stage" >&2
	exit 1
fi

initramfs="`pwd`/build/initramfs-${kernel_version}.img"
env \
	CT_XLDD_ROOT="$r00tfs" \
	DRACUT_LDD=`pwd`/${TARGET}-ldd \
	DRACUT_TESTBIN="$r00tfs/usr/bin/bash" \
	DRACUT_INSTALL="${xtools}${build_prefix}/lib/dracut/dracut-install --verbose --debug" \
	DRACUT_INSTALL_PATH='/usr/bin:/usr/sbin' \
	DRACUT_PATH="/usr/bin /usr/sbin" \
	${xtools}${build_prefix}/bin/dracut \
		--verbose \
		--debug \
		--force \
		--kver $kernel_version \
		--sysroot "$r00tfs" \
		--gzip \
	"${initramfs}.tmp"

rm -rf "${initramfs%.img}"
mkdir -p "${initramfs%.img}"
cd "${initramfs%.img}"
zcat "${initramfs}.tmp" | cpio -imd
relocate_to_usr "`pwd`"
find . | fakeroot cpio -H newc --create | ( cd .. ; pigz -9 > "$initramfs" )
cd ../..
cp -a "$initramfs" "$r00tfs/boot"

# RECIPE END initramfs
